<template>
  <div class="photoModule publicHCenter">
    <div class="photoBox" :class="{ show: isShowAni }">
      <img src="https://static.hudongmiao.com/joymewH5/img/popupArea/loveBubble.png" class="loveBubbleImg1" />
      <img src="https://static.hudongmiao.com/joymewH5/img/popupArea/loveBubble.png" class="loveBubbleImg2" />
      <div class="title">现场照片</div>
      <div class="note">您发送的图片会展示在大屏幕上，快来试试吧！</div>
      <div class="sizeWrap">
        <div
          class="item publicHvCenter"
          v-for="item in photoTypeList_display"
          :key="item.id"
          :class="[item.size, { active: currentPhotoType === item.giftId }]"
          v-tap="{ methods: choosePhotoType, giftId: item.giftId }"
        >
          <div class="price publicHvCenter" v-if="!item.isFree">
            {{ item.price }}<img src="@/assets/image/icon/diamond.png" class="unit" />
          </div>
          <div class="price publicHvCenter" v-if="item.isFree">免费</div>
          <div class="size publicHvCenter">{{ item.name }}</div>
          <div class="time">{{ item.time }}s</div>
        </div>
      </div>
      <div class="txtWrap publicHCenter">
        <textarea
          v-model="content"
          maxlength="40"
          ref="text"
          cols="30"
          rows="10"
          placeholder="输入您的祝福(40字以内)"
          v-on:blur="handleBlur"
        ></textarea>
        <div class="photoWrap publicHvCenter">
          <img src="https://static.hudongmiao.com/joymewH5/img/popupArea/camera.png" class="cameraImg" />
          <img :src="previewImg" class="previewImg" v-show="hasUpload" v-tap="{ methods: showPreview }" />
          <input ref="fileinput" accept="image/*" type="file" class="file" @change="change" v-show="!hasUpload" />
        </div>
      </div>
      <div class="btnWrap publicHCenter">
        <div class="btn publicHvCenter" v-tap="{ methods: sendPhoto }">发送</div>
      </div>
    </div>
    <div class="previewBox publicVCenter" v-if="previewShow">
      <img :src="previewImg" />
      <div class="btnGroup">
        <div v-tap="{ methods: cancelPreview }">取消</div>
        <div v-tap="{ methods: confirmPreview }">确定</div>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
import { timeoutTask } from '@/utils/index';
import { uploadPhoto, sendPhotoGift } from '@/api/index/index';
import { sendPhotoGiftMessage } from '@/api/chat/index';
import { POPUP_MODULE } from '@/assets/constant/index';

export default {
  name: 'photoPopup',
  computed: {
    ...mapState({
      previewImg: (state) => state.app.previewImg,
      photoTypeList: (state) => state.live.photoTypeList,
      currentPhotoType: (state) => state.app.currentPhotoType,
      money: (state) => state.user.money,
      freeSendGift: (state) => state.user.freeSendGift,
      isFreeSendPhoto: (state) => state.live.isFreeSendPhoto,
    }),
    photoTypeList_display() {
      let tmpList;
      if (this.isFreeSendPhoto) {
        tmpList = this.photoTypeList.map((item) => {
          return {
            ...item,
            isFree: item.size === 'small',
          };
        });
      } else {
        tmpList = this.photoTypeList;
      }
      return tmpList;
    },
  },
  created() {},
  mounted() {
    // 执行弹出动画
    this.showAniStart();
  },
  data() {
    return {
      isShowAni: false, // 控制bapin box弹出动画
      hasUpload: false,
      previewShow: false,
      content: '',
    };
  },
  methods: {
    ...mapMutations({
      setPreviewImg: 'app/setPreviewImg',
      resetPreviewImg: 'app/resetPreviewImg',
      setCurrentPhotoType: 'app/setCurrentPhotoType',
      setUserInfo: 'user/setUserInfo',
      togglePopup: 'app/togglePopup',
      setOrigin: 'app/setOrigin',
    }),
    handleBlur() {
      window.scrollTo(0, -document.documentElement.clientHeight);
    },
    showAniStart() {
      timeoutTask(() => {
        this.isShowAni = true;
      }, 100);
    },
    hideAniStart() {
      this.isShowAni = false;
    },
    change(e) {
      try {
        this.$loading('图片加载中...');
        const freader = new FileReader();
        const file = e.target.files[0];
        // const fixOrientation = require('fix-orientation');

        freader.onload = (ev) => {
          const url = ev.target.result;
          this.setPreviewImg(url);
          this.previewShow = true;
          this.hasUpload = true;
          this.$loading.close();
          // fixOrientation(
          //   url,
          //   {
          //     image: true,
          //   },
          //   (fixedImg) => {
          //     this.setPreviewImg(fixedImg);
          //     this.previewShow = true;
          //     this.hasUpload = true;
          //     this.$loading.close();
          //   }
          // );
        };

        freader.onerror = () => {
          this.$loading.close();
          this.$toast.center('图片加载失败');
        };

        freader.readAsDataURL(file); // 读取照片
      } catch (err) {
        this.$loading.close();
      }
    },
    showPreview() {
      this.previewShow = true;
    },
    cancelPreview() {
      this.hasUpload = false;
      this.resetPreviewImg();
      this.$refs.fileinput.value = '';
      this.previewShow = false;
    },
    confirmPreview() {
      this.previewShow = false;
    },
    choosePhotoType(p) {
      this.setCurrentPhotoType(p.giftId);
    },
    sendPhoto() {
      // 发送前的验证
      if (!this.validateSend()) {
        return;
      }
      this.$loading('发送祝福中...');
      this.uploadPhoto().then((res1) => {
        console.log('***上传照片***');
        console.log(res1);
        this.setPreviewImg(res1.filePath);
        return sendPhotoGift(this.content, this.previewImg)
          .then((res2) => {
            // 更新 用户余额
            this.setUserInfo({
              money: res2.result.balance,
            });
            return this.sendBroadcast(); // 发送礼物的广播
          })
          .then((res3) => {
            console.log(res3);
            this.$loading.close();
            this.$toast.center('发送成功!');
            // 清空数据
            this.hasUpload = false;
            this.content = '';
            this.resetPreviewImg();
            this.togglePopup();
            this.$refs.text.blur();
          })
          .catch((err) => {
            console.log(err);
            this.$loading.close();
            this.$toast.center('发送失败!');
          });
      });
    },
    validateSend() {
      let flag = true;
      const choosedPhotoType = this.photoTypeList_display.find((item) => item.giftId === this.currentPhotoType);
      if (!this.content) {
        flag = false;
        this.$toast.center('请输入您的祝福!');
      } else if (!this.previewImg) {
        flag = false;
        this.$toast.center('请选择您发送的图片');
      } else if (this.freeSendGift) {
        // 免费发礼物
        flag = true;
      } else if (choosedPhotoType.isFree) {
        // 本场免费发照片
        flag = true;
      } else if (choosedPhotoType.price > this.money) {
        this.$toast.center('余额不足,请充值!');
        flag = false;
        this.setOrigin('sendPhoto');
        this.togglePopup();
        timeoutTask(() => {
          this.togglePopup(POPUP_MODULE.rechargeModule.key);
        }, 200);
      }
      return flag;
    },
    uploadPhoto() {
      const formData = new FormData();
      const arr = this.previewImg.split(',');
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      /* eslint-disable */
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      const file = new File([u8arr], 'photo');
      formData.append('file', file);
      formData.append('prefix', 'love');
      return uploadPhoto(formData);
    },
    sendBroadcast() {
      return sendPhotoGiftMessage(this.content, this.previewImg);
    },
  },
};
</script>
<style lang="less" scoped>
.photoModule {
  position: absolute;
  width: 100%;
  height: 708px;
  bottom: 0;
  .photoBox {
    width: 750px;
    height: 708px;
    background-image: url(https://static.hudongmiao.com/joymewH5/img/popupArea/box.png);
    background-size: 100% 100%;
    background-repeat: no-repeat;
    transition: all 0.2s linear;
    position: absolute;
    top: 708px;
    &.show {
      transform: translateY(-708px);
    }
    .loveBubbleImg1 {
      width: 108px;
      height: 117px;
      position: absolute;
      top: -46px;
      left: 182px;
    }
    .loveBubbleImg2 {
      width: 108px;
      height: 117px;
      position: absolute;
      top: -10px;
      left: 474px;
    }
    .title {
      font-size: 40px;
      font-weight: normal;
      font-stretch: normal;
      letter-spacing: 8px;
      color: #ffffff;
      text-align: center;
      margin-top: 32px;
      text-align: center;
      text-shadow: #9316c2 1px 1px 0, #9316c2 -1px -1px 0, #9316c2 1px -1px 0, #9316c2 -1px 1px 0, #9316c2 2px 2px 0, #9316c2 -2px -2px 0,
        #9316c2 2px -2px 0, #9316c2 -2px 2px 0, #9316c2 3px 3px 0, #9316c2 -3px -3px 0, #9316c2 3px -3px 0, #9316c2 -3px 3px 0,
        #9316c2 4px 4px 0, #9316c2 -4px -4px 0, #9316c2 -4px 4px 0, #9316c2 4px -4px 0, #9316c2 5px 5px 0, #9316c2 -5px -5px 0,
        #9316c2 -5px 5px 0, #9316c2 5px -5px 0;
    }
    .note {
      font-size: 24px;
      color: #ffffff;
      letter-spacing: 1px;
      text-align: center;
      margin-top: 29px;
    }
    .sizeWrap {
      width: 100%;
      height: 157.5px;
      margin-top: 44px;
      display: flex;
      justify-content: space-around;
      .item {
        width: 160px;
        height: 160px;
        border-radius: 8px;
        position: relative;
        flex-direction: column;
        &.small {
          background-color: rgba(211, 7, 185, 0.1);
          .size {
            width: 36px;
            height: 36px;
            font-size: 20px;
          }
        }
        &.mid {
          background-color: rgba(211, 7, 185, 0.2);
          .size {
            width: 46px;
            height: 46px;
            font-size: 24px;
          }
        }
        &.large {
          background-color: rgba(211, 7, 185, 0.3);
          .size {
            width: 56px;
            height: 56px;
            font-size: 28px;
          }
        }
        &.ba {
          background-color: rgba(211, 7, 185, 0.4);
          .size {
            width: 56px;
            height: 56px;
            font-size: 28px;
          }
        }
        &.active {
          border-style: solid;
          border-width: 4px;
          border-image-source: linear-gradient(0deg, #b86afa 0%, #ff536b 100%);
          border-image-slice: 1;
        }
        .price {
          width: 102px;
          height: 34px;
          background-image: url(https://static.hudongmiao.com/joymewH5/img/popupArea/priceBox-danmu.png);
          background-size: 100% 100%;
          position: absolute;
          top: -27px;
          right: 30px;
          font-size: 24px;
          color: #8a4e41;
          letter-spacing: 1px;
          .unit {
            width: 28px;
            height: 21px;
            margin-left: 6px;
          }
        }
        .size {
          color: #ffffff;
          border-radius: 50%;
          margin-top: 7.5px;
          border: solid 1px #ffffff;
        }
        .time {
          font-size: 28px;
          letter-spacing: 1px;
          color: #ffffff;
          margin-top: 19px;
        }
      }
    }
    .txtWrap {
      margin-top: 27px;
      position: relative;
      textarea {
        width: 670px;
        height: 210px;
        background-color: rgba(255, 255, 255, 0.2);
        border-radius: 8px;
        font-size: 28px;
        padding: 25px 32px;
        color: #ffffff;
        box-sizing: border-box;
        outline: none;
        border: none;
        &::placeholder {
          font-size: 28px;
          color: #ffffff;
        }
      }
      .photoWrap {
        width: 60px;
        height: 60px;
        background-color: #ffffff;
        position: absolute;
        bottom: 20px;
        right: 78px;
        border-radius: 50%;
        .cameraImg {
          width: 38px;
          height: 29px;
        }
        .previewImg {
          position: absolute;
          width: 90px;
          height: 90px;
          bottom: 0;
          right: 0;
        }
        .file {
          position: absolute;
          width: 60px;
          height: 60px;
          opacity: 0;
        }
      }
    }
    .btnWrap {
      width: 100%;
      height: 80px;
      margin-top: 22.5px;
      .btn {
        width: 500px;
        height: 80px;
        background-image: url(https://static.hudongmiao.com/joymewH5/img/popupArea/btnBg.png);
        border-radius: 6px;
        font-size: 34px;
        letter-spacing: 3px;
        color: #a24935;
      }
    }
  }
  .previewBox {
    width: 100vw;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    background: #000;
    img {
      width: 100vw;
    }
    .btnGroup {
      width: 100%;
      height: 10vh;
      background-color: #000;
      display: flex;
      position: absolute;
      left: 0;
      bottom: 0;
      div {
        color: #fff;
        width: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
}
</style>
